package com.yang.chatTtl.controller;

import jakarta.annotation.Resource;
import org.springframework.ai.openai.OpenAiAudioSpeechClient;
import org.springframework.ai.openai.OpenAiAudioSpeechOptions;
import org.springframework.ai.openai.api.OpenAiAudioApi;
import org.springframework.ai.openai.audio.speech.SpeechPrompt;
import org.springframework.ai.openai.audio.speech.SpeechResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.FileOutputStream;
import java.io.IOException;

@RestController
public class TtlController {
     @Resource
    private OpenAiAudioSpeechClient openAiAudioSpeechClient;
    @GetMapping("/ai/ttl")
    public void textToVoice(){
        String text="霜月落亭前 朝谁也无眠 提笔紧绕烛火 回忆难写";
        SpeechResponse response = openAiAudioSpeechClient.call(
                new SpeechPrompt(
                        text, OpenAiAudioSpeechOptions
                        .builder()
                        .withVoice(OpenAiAudioApi.SpeechRequest.Voice.ALLOY)
                        .withResponseFormat(OpenAiAudioApi.SpeechRequest.AudioResponseFormat.MP3)
                        .withModel("tts-1-hd")
                        .withSpeed(1.0f)
                        .build()
                )
        );
        byte[] output = response.getResult().getOutput();
        String filePath = "D:\\code\\SpringAI\\ChatTtl\\src\\main\\resources\\output.mp3";
        try {
            saveAudioToFile(output, filePath);
        } catch (IOException e) {
            // 处理保存文件时的异常
            e.printStackTrace();
        }

    }
    public static void saveAudioToFile(byte[] audioData, String filePath) throws IOException {
        try (FileOutputStream fos = new FileOutputStream(filePath)) {
            fos.write(audioData);
        }
    }
}
